package com.liangtian.mdm.util;

import com.liangtian.mdm.base.utils.PlatForm;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;

public class ExportUtil {

    private static Logger log = LoggerFactory.getLogger(ExportUtil.class);

    /**
     * 模板导出通用方法
     *
     * @param path           文件路径
     * @param fileName       文件名
     * @param uploadFileName 下载文件名
     * @param response
     */
    public static void exportTemplate(String path, String fileName, String uploadFileName, HttpServletResponse response) {
        InputStream inStream = null;
        OutputStream outStream = null;
        try {
            System.out.println("fileName=='" + fileName + "'");
            File file = new File(path, fileName);
            inStream = new FileInputStream(file);
            byte[] bytes = new byte[1024];
            int len;
            outStream = response.getOutputStream();
            ExcelUtil.setResponseHeader(response, uploadFileName);
            while ((len = inStream.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
            }
            outStream.flush();
            outStream.close();
        } catch (FileNotFoundException e) {
            log.info(path + "\\" + fileName + "文件不存在");
            log.info(e.getMessage());
        } catch (IOException e) {
            log.info(e.getMessage());
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (Exception e) {
                }
            }
        }
    }

    /**
     * 写入错误文件(将错误日志,文件之类的内容写入到服务器上)
     *
     * @param errText
     * @param fileName
     * @author wy
     */
    public static void errTxt(String errText, String fileName) throws IOException {
        String[] strs = errText.split("@@");
        StringBuilder sbStr = new StringBuilder();
        for (String str : strs) {
            sbStr.append(str);
        }
        String path = getModelPath() + "/" + fileName;
        log.info("---错误文件路径---{}", path);
        writeInJsp(sbStr.toString(), path);
    }

    /**
     * 将字符串写入jsp目标文件
     *
     * @param str            输入的字符串
     * @param targetFilePath 目标文件路径
     * @throws IOException
     */
    public static void writeInJsp(String str, String targetFilePath) throws IOException {
        OutputStreamWriter outWrite = null;
        try {
//        	outWrite = new OutputStreamWriter(new FileOutputStream(new File(targetFilePath)),"UTF-8");
            outWrite = new OutputStreamWriter(new FileOutputStream(targetFilePath), "UTF-8");// 新建文件输出流并对它进行缓冲
            outWrite.write(str);
            outWrite.flush();// 刷新此缓冲的输出流
        } finally {
            // 关闭流
            if (outWrite != null) {
                outWrite.close();
            }
        }
    }

    /**
     * 读取错误文件(从服务器上读取错误日志,文件)
     *
     * @param
     * @param fileName
     * @author wy
     */
    public static void getErrText(String fileName, HttpServletRequest request, HttpServletResponse response) throws IOException {
        String file = getModelPath() + "/" + fileName;
        log.info("---wangyue---jspAC--file-:" + file);
        InputStream inStream = new FileInputStream(file);
        try {
            //解决中文文件名乱码问题
            if (request.getHeader("User-Agent").toUpperCase().indexOf("MSIE") > 0) {
                fileName = URLEncoder.encode(fileName, "UTF-8");//IE浏览器
            } else {
                fileName = new String(fileName.getBytes("UTF-8"), "ISO8859-1");//firefox浏览器
            }
            response.reset();
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/octet-stream; charset=UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=\"" + fileName + "\"");
            // 循环取出流中的数据
            byte[] b = new byte[100];
            int len;
            OutputStream output = response.getOutputStream();
            while ((len = inStream.read(b)) > 0) {
                output.write(b, 0, len);
            }

            output.flush();
            output.close();
            inStream.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inStream != null) {
                try {
                    inStream.close();
                } catch (Exception e) {
                }
            }
        }
    }

    public static String getModelPath() {
        String filePath = PlatForm.getAbsolutePath() + "error_text";
        File file = new File(filePath);
        //判断文件夹是否存在，不存在则创建
        if (!file.exists()) {
            file.mkdir();
        }
        return filePath;
//		return "";
    }

}
